package org.kwin.ibatis.session;

import org.kwin.ibatis.proxy.MapperProxyFactory;
import org.kwin.ibatis.util.MySQLUtil;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author : wangkai
 * @version V1.0
 * @Package org.kwin.ibatis.session
 * @Description:
 * @date 2021年10月09日 14:00
 **/
public class SqlSession {
    private Connection connection;
    private boolean transaction;
    
    public Connection getConnection() {
        return connection;
    }
    
    public boolean isTransaction() {
        return transaction;
    }
    
    protected SqlSession(Connection connection)
    {
        this.connection = connection;
        this.transaction = false;
    }
    
    protected SqlSession(Connection connection, boolean transaction)
    {
        this.connection = connection;
        this.transaction = transaction;
    }

    public void beginTransaction() {
        if (connection != null) {
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                System.out.println("begin transaction failure");
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
    
    public void commitTransaction() {
        if (connection != null) {
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("rollback transaction failure");
                throw new RuntimeException(e);
            } finally {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
    
    public void rollbackTransaction() {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("rollback transaction failure");
                throw new RuntimeException(e);
            } finally {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
